package org.budo.warehouse.logic.consumer.mapping;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.budo.support.lang.util.ListUtil;
import org.budo.warehouse.logic.api.AbstractDataConsumerWrapper;
import org.budo.warehouse.logic.api.DataEntry;
import org.budo.warehouse.logic.api.DataMessage;
import org.budo.warehouse.logic.api.DataMessagePojo;
import org.budo.warehouse.service.api.IFieldMappingService;
import org.budo.warehouse.service.entity.FieldMapping;
import org.budo.warehouse.service.entity.Pipeline;

import lombok.Getter;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
public class FieldMappingDataConsumerWrapper extends AbstractDataConsumerWrapper {
    @Resource
    private IFieldMappingService fieldMappingService;

    @Override
    public void consume(DataMessage dataMessage) {
        Pipeline pipeline = this.getPipeline();
        DataMessage fieldMappingMessage = this.fieldMappingMessage(pipeline, dataMessage);
        this.getDataConsumer().consume(fieldMappingMessage);
    }

    private DataMessage fieldMappingMessage(Pipeline pipeline, DataMessage dataMessage) {
        Boolean originalFields = fieldMappingService.findOriginalFieldsValueByPipelineIdCached(pipeline.getId());
        List<FieldMapping> fieldMappings = fieldMappingService.listByPipelineIdCached(pipeline.getId()); // 字段对应关系
        if (null == originalFields) {
            originalFields = ListUtil.isNullOrEmpty(fieldMappings); // 如果未配置originalFields就以对应关系是否为空判断
        }

        List<DataEntry> dataEntries = dataMessage.getDataEntries();
        List<DataEntry> fieldMappingDataEntries = new ArrayList<DataEntry>(dataEntries.size());
        for (DataEntry dataEntry : dataEntries) {
            FieldMappingDataEntry fieldMappingDataEntry = new FieldMappingDataEntry(dataEntry, pipeline, originalFields, fieldMappings);
            fieldMappingDataEntries.add(fieldMappingDataEntry);
        }

        Integer dataNodeId = dataMessage.getDataNodeId();
        return new DataMessagePojo(dataMessage.getId(), dataNodeId, fieldMappingDataEntries);
    }
}